#!/bin/bash

# 参数说明：
# $1: App名称 (如 "MyApp")
# $2: 打包环境 (如 "debug", "release", "staging")
# $3: 包名 (如 "com.example.myapp")
# $4: API域名 (如 "https://api.example.com")
# $5: H5域名 (如 "https://h5.example.com")

# 检查参数是否完整
if [ $# -ne 5 ]; then
    echo "Usage: $0 <AppName> <Env> <PackageName> <ApiDomain> <H5Domain>"
    exit 1
fi

APP_NAME="$1"
ENV="$2"
PACKAGE_NAME="$3"
API_DOMAIN="$4"
H5_DOMAIN="$5"

# 进入项目根目录（根据实际情况调整）
PROJECT_DIR=$(dirname "$0")
cd "$PROJECT_DIR" || exit

# 1. 修改 build.gradle (动态配置包名和构建类型)
sed -i '' "s/applicationId \".*\"/applicationId \"$PACKAGE_NAME\"/g" app/build.gradle
sed -i '' "s/buildConfigField \"String\", \"BASE_API\", \".*\"/buildConfigField \"String\", \"BASE_API\", \"$API_DOMAIN\"/g" app/build.gradle

# 2. 修改 strings.xml (动态配置App名称和H5域名)
sed -i '' "s/<string name=\"app_name\">.*<\/string>/<string name=\"app_name\">$APP_NAME<\/string>/g" app/src/main/res/values/strings.xml
sed -i '' "s/<string name=\"h5_domain\">.*<\/string>/<string name=\"h5_domain\">$H5_DOMAIN<\/string>/g" app/src/main/res/values/strings.xml

# 3. 修改 AndroidManifest.xml (可选，如需动态包名)
sed -i '' "s/package=\".*\"/package=\"$PACKAGE_NAME\"/g" app/src/main/AndroidManifest.xml

# 4. 执行Gradle打包命令
echo "Building $APP_NAME ($ENV) with package $PACKAGE_NAME..."
./gradlew "assemble$(tr '[:lower:]' '[:upper:]' <<< ${ENV:0:1})${ENV:1}"  # 转换为首字母大写的构建命令，如 assembleRelease

# 5. 输出APK路径
APK_PATH=$(find app/build/outputs/apk -name "*.apk" | head -n 1)
echo "APK generated at: $APK_PATH"


#/build_android.sh "MyApp" "debug" "com.test.app" "https://dev.api.com" "https://dev.h5.com"